package com.anhry.app.safety.util.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.anhry.app.safety.dao.base.SuperDao;
import com.anhry.app.safety.manage.system.bean.TbActionLog;
import com.anhry.app.safety.manage.system.bean.TbUser;
import com.anhry.app.safety.util.DateFormater;
import com.anhry.app.safety.util.Loggers;
import com.anhry.app.safety.util.Param;
import com.anhry.app.safety.util.UtilMethod;
import com.anhry.app.safety.util.dao.UtilDao;

@Repository
public class UtilDaoImpl extends SuperDao implements UtilDao{

	@Transactional
	public void delete(Object obj) throws Exception {
		getHibernateTemplate().delete(obj);
	}

	public Object getObjectById(Class classes, String id) throws Exception {
		Session session = getHibernateTemplate().getSessionFactory().openSession();
		Transaction tr = session.beginTransaction();
		Object obj=null;
		try{
			obj=session.get(classes,id);
			tr.commit();
			return obj;
		}catch(Exception e){
			if(tr != null){
				tr.rollback();
			}
			e.printStackTrace();
			throw e;
		}finally{
			if(session != null & session.isOpen()){
				session.clear();
				session.close();
			}
		}
	}

	public Object getObjectById(Class classes, int id) throws Exception {
		Session session = getHibernateTemplate().getSessionFactory().openSession();
		Transaction tr = session.beginTransaction();
		Object obj=null;
		try{
			obj=session.get(classes,id);
			tr.commit();
			return obj;
		}catch(Exception e){
			if(tr != null){
				tr.rollback();
			}
			e.printStackTrace();
			throw e;
		}finally{
			if(session != null & session.isOpen()){
				session.clear();
				session.close();
			}
		}
	}
	
	public Object getObjectById(Class classes, Long id) throws Exception {
		Session session = getHibernateTemplate().getSessionFactory().openSession();
		Transaction tr = session.beginTransaction();
		Object obj=null;
		try{
			obj=session.get(classes,id);
			tr.commit();
			return obj;
		}catch(Exception e){
			if(tr != null){
				tr.rollback();
			}
			e.printStackTrace();
			throw e;
		}finally{
			if(session != null & session.isOpen()){
				session.clear();
				session.close();
			}
		}
	}
	
	@Transactional(propagation=Propagation.REQUIRED)
	public void save(Object obj) throws Exception {
		try {
			this.getHibernateTemplate().save(obj);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	/* (non-Javadoc)
	 * 创建或更新一个对象
	 */
	@Transactional(propagation=Propagation.REQUIRED)
	public void saveOrUpdate(Object obj) throws Exception{
		Session session = getHibernateTemplate().getSessionFactory().openSession();
		Transaction tr = session.beginTransaction();
		try{
			session.saveOrUpdate(obj);
			session.flush();
			tr.commit();
		}catch(Exception e){
			if(tr != null){
				tr.rollback();
			}
			e.printStackTrace();
			Loggers.error("saveOrUpdate保存或修改对象错误"+e);
			throw e;
		}finally{
			if(session != null & session.isOpen()){
				session.clear();
				session.close();
			}
		}
	}
	
	@Transactional(propagation=Propagation.REQUIRED)
	public void update(Object obj) throws Exception {
		try {
			this.getHibernateTemplate().update(obj);
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error(obj+"对象修改错误"+e);
		}
		
	}
	
	@Transactional(propagation=Propagation.REQUIRED)
	public void merge(Object obj) throws Exception {
		try {
			this.getHibernateTemplate().merge(obj);
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error(obj+"对象merge错误"+e);
		}
	}
	
	
	public Object getCollection(String objName, List<Param> params, Map orders, int start, int count) throws Exception{
		Session session = null;
		Query query = null;
		try {
			// 组合检索语句
			String strSQL = null;
			StringBuffer strBuff = new StringBuffer();
			if(count == 0)
				strBuff.append("select count(*) from ");
			else
				strBuff.append("from ");
			strBuff.append(objName);
			strBuff.append(" d");
			if (params != null && params.size() > 0) {
				strBuff.append(" where 1=1 ");
				for (Param param : params) {
					strBuff.append(" and d.");
					strBuff.append(param.getParamName());
					if (param.getOperator().trim().equals("in")) {
						strBuff.append(" " + param.getOperator() + "(");
						strBuff.append(param.getParamValue());
						strBuff.append(")");
					} else if (param.getOperator().trim().equals("like")) {
						strBuff.append(" " + param.getOperator());
						strBuff.append(" '%" + param.getParamValue()+"%'");
					} else if (param.getOperator().trim().equals("between")){
						strBuff.append(" " + param.getOperator());
						String date[] = UtilMethod.separator((String)param.getParamValue(), ",");	//2000-01-01,2000-02-02 格式化成数组
						strBuff.append(" "+date[0]+"  00:00:00"+" and "+date[1]+" 23:59:59");
					} else {
						strBuff.append(param.getOperator());
						strBuff.append("'" + param.getParamValue()+"'");
					}
				}
			}
			if (orders != null && !orders.isEmpty()) {
				strBuff.append(" order by ");
				for (Iterator it = orders.keySet().iterator(); it.hasNext();) {
					String orderName = (String) it.next();
					strBuff.append("d.");
					strBuff.append(orderName);
					strBuff.append(" ");
					strBuff.append((String) orders.get(orderName));
					strBuff.append(",");
				}
				strBuff.setLength(strBuff.length() - 1);
			}
			strSQL = new String(strBuff);
//			System.out.println("查询集合:getCollection()--: "+strSQL);
			session = getHibernateTemplate().getSessionFactory().openSession();
			query = session.createQuery(strSQL);
			if(count > 0){
				query.setFirstResult(start);
				query.setMaxResults(count);
			}
			if(count == 0){
				List list = query.list();	//查询记录总数
				if(list != null && list.size() > 0){
					return Integer.parseInt(list.get(0).toString());
				}
			}
			return query.list();
		} catch (HibernateException e) {
			Loggers.error("------查询集合公用方法错误：UtilDaoImpl getCollection"+e);
			throw new HibernateException(e.getMessage());
		}finally{
			if(session != null && session.isOpen()){
				session.clear();
				session.close();
			}
		}
	}
	
	public Object getHqlQuery(String hql) throws Exception{
		return getHibernateTemplate().find(hql);
	}
	
	public Collection getHqlQuery(String hql,final int start,final int count) throws Exception{
		final String strSQL = hql;
		Collection collection = (Collection) getHibernateTemplate().execute(new HibernateCallback(){
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Query query = session.createQuery(strSQL);
				if(count > 0 ){
					query.setFirstResult(start);
					query.setMaxResults(count);
				}						
				return query.list();
			}
		});
		return collection;
	}
	
	public int getHqlQuerySize(String hql) throws Exception{
		return Integer.parseInt(getHibernateTemplate().find(hql).get(0).toString());
	}
	
	@Transactional(propagation=Propagation.REQUIRED)
	public void updateAll(String objName,Map sets, List<Param> params) throws Exception{
		Session session = null;
		Query query = null;
		String strSQL = null;
		try {
			StringBuffer strBuff = new StringBuffer();
			strBuff.append("update ");
			strBuff.append(objName);
			strBuff.append(" d ");
			if(sets != null && !sets.isEmpty()){
				strBuff.append(" set ");
				for (Iterator it = sets.keySet().iterator(); it.hasNext();) {
					String setName = (String) it.next();
					strBuff.append(" d.");
					strBuff.append(setName);
					strBuff.append("='");
					strBuff.append(sets.get(setName));
					strBuff.append("',");
				}
				strBuff.setLength(strBuff.length() - 1);	//去,号
			}
			if (params != null && params.size() > 0) {
				strBuff.append(" where ");
				for (Iterator it = params.iterator(); it.hasNext();) {
					Param param = (Param) it.next();
					strBuff.append("d.");
					strBuff.append(param.getParamName());
					if (param.getOperator().trim().equals("in")) {
						strBuff.append(" " + param.getOperator() + "(");
						strBuff.append(param.getParamValue());
						strBuff.append(") and ");
					} else if (param.getOperator().trim().equals("like")) {
						strBuff.append(" " + param.getOperator());
						strBuff.append(" '%" + param.getParamValue());
						strBuff.append("%' and ");
					} else {
						strBuff.append(param.getOperator());
						strBuff.append(":" + param.getParamName());
						strBuff.append(" and ");
					}
				}
				strBuff.setLength(strBuff.length() - 5);	//去" and "
			}
			strSQL = new String(strBuff);
//			System.out.println("更新对象updateAll()--: "+strSQL);
			Loggers.debug(strSQL);
			session = getHibernateTemplate().getSessionFactory().openSession();
			query = session.createQuery(strSQL);
			if (params != null && !params.isEmpty()) {
				for (Iterator it = params.iterator(); it.hasNext();) {
					Param param = (Param) it.next();
					if (!param.getOperator().trim().equals("in")
							&& !param.getOperator().trim().equals("like")) {
						query.setParameter(param.getParamName(), param.getParamValue());
					}
				}
			}
			query.executeUpdate();
		} catch (HibernateException e) {
			e.printStackTrace();
			Loggers.error("------更新对象错误：UtilDaoImpl updateAll");
		}finally{
			if(session != null && session.isOpen()){
				session.clear();
				session.close();
			}
		}
	}
	
	@Transactional(propagation=Propagation.REQUIRED)
	public void deleteAll(String objName, List<Param> params) throws Exception{
		Session session = null;
		Query query = null;
		String strSQL = null;
		try {
			StringBuffer strBuff = new StringBuffer();
			strBuff.append("delete from ");
			strBuff.append(objName);
			strBuff.append(" d");
			if (params != null && params.size() > 0) {
				strBuff.append(" where ");
				for (Iterator it = params.iterator(); it.hasNext();) {
					Param param = (Param) it.next();
					strBuff.append("d.");
					strBuff.append(param.getParamName());
					if (param.getOperator().trim().equals("in")) {
						strBuff.append(" " + param.getOperator() + "(");
						strBuff.append(param.getParamValue());
						strBuff.append(") and ");
					} else if (param.getOperator().trim().equals("like")) {
						strBuff.append(" " + param.getOperator());
						strBuff.append(" '%" + param.getParamValue());
						strBuff.append("%' and ");
					} else {
						strBuff.append(param.getOperator());
						strBuff.append(":" + param.getParamName());
						strBuff.append(" and ");
					}
				}
				strBuff.setLength(strBuff.length() - 5);	//去" and "
			}
			strSQL = new String(strBuff);
//			System.out.println("删除对象deleteAll()--: "+strSQL);
			Loggers.debug(strSQL);
			session = getHibernateTemplate().getSessionFactory().openSession();
			query = session.createQuery(strSQL);
			if (params != null && !params.isEmpty()) {
				for (Iterator it = params.iterator(); it.hasNext();) {
					Param param = (Param) it.next();
					if (!param.getOperator().trim().equals("in")
							&& !param.getOperator().trim().equals("like")) {
						query.setParameter(param.getParamName(), param.getParamValue());
					}
				}
			}
			query.executeUpdate();
		} catch (HibernateException e) {
			e.printStackTrace();
			Loggers.error("------删除对象错误：UtilDaoImpl deleteAll");
		}finally{
			if(session != null && session.isOpen()){
				session.clear();
				session.close();
			}
		}

	}

	public List getFjList(String classes, String id) throws Exception {
		return this.getHibernateTemplate().find("from "+classes+" fj where fj.tbObject.id='"+id+"' order by fj.id");
	}
	@Transactional(propagation=Propagation.REQUIRED)
	public void deleteBySql(String sql) throws Exception {
		Session session = null;
		try {
			session = getHibernateTemplate().getSessionFactory().openSession();
			Transaction tx = session.beginTransaction();    
			Connection con=session.connection();    
			PreparedStatement stmt=con.prepareStatement(sql);    
			stmt.executeUpdate();    
			tx.commit();  
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("------批量删除错误：UtilDaoImpl deleteBySql(String sql)");
		}finally{
			if(session != null && session.isOpen()){
				session.clear();
				session.close();
			}
		}
	}

	public List getObjectBySql(final String sql,final int start,final int count)throws Exception {
		List list = (List)this.getHibernateTemplate().execute(new HibernateCallback(){

			public Object doInHibernate(Session session)throws HibernateException, SQLException {
				List list = new ArrayList();
				try {
					Query query = session.createSQLQuery(sql);
					if(count > 0){
						query.setFirstResult(start);
						query.setMaxResults(count);
					}
					return query.list();
				} catch (RuntimeException e) {
					Loggers.error("UtilDaoImpl:getObjectBySql()出错："+e);
					e.printStackTrace();
				}
				return list;
			}
		});
		return list;
	}
	public String getObjectBySql(String sql) throws Exception {
		String size = "0";
		List list = null;
		Session s = getHibernateTemplate().getSessionFactory().openSession();
		try {
			SQLQuery query = s.createSQLQuery(sql);
			list = query.list();
			if(list != null && list.size()>0){
				Object temp = (Object) list.get(0);
				if(temp != null && !"".equals(temp.toString())){
					size = temp.toString();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("UtilDaoImpl:getObjectBySql()出错："+e.getMessage());
		}
		finally{
			if(s != null && s.isOpen()){
				s.close();
			}
		}
		return size;
	}
	public <T> T getObject(Class<T> clazz, String ID) throws Exception {
	    String className = clazz.getName();
	    String simpleClassName = className.substring(className.lastIndexOf(".")+1);
	    List<T> list = (List<T>)getHqlQuery("from " + simpleClassName + " o where o.ID='" + ID +"' order by o.synTime desc");
	    if(null!=list && list.size()>0){
	    	return list.get(0);
	    }
	    return null;
	}
	
	
	public void close(Session s) throws Exception {
		if(s != null && s.isOpen()){
			s.close();
		}
	}

	public Session getHibernateSession() throws Exception {
		return getHibernateTemplate().getSessionFactory().openSession();
	}
	
	public void evict(Object o) throws Exception {
		getHibernateTemplate().evict(o);
	}
	
	public void saveActionLog(TbUser user, String log) throws Exception {
		TbActionLog obj = new TbActionLog();
		obj.setActionDate(new Date());
		obj.setActionInfo(DateFormater.formatDateTime(new Date())+log);
		obj.setIsDele("0");
		if(null!=user){
			obj.setUserId(user.getId());
			obj.setUserName(user.getUserName());
		}else{
			obj.setUserName("系统任务调度");
		}
		this.save(obj);
	}
	
}
